<?php
/**
 * @Notes 内容类.
 * @author: ysongyang <ysongyang@qq.com>
 * @link
 * @copyright: copyright 2017 ysongyang all rights reserved.
 * @license http://www.apache.org/licenses/LICENSE-2.0
 */

namespace app\index\controller;

use app\model\Category;
use app\model\Collection;
use app\model\ExperienceLog;
use think\Db;

class Forum extends Base
{

    public function _initialize()
    {
        parent::_initialize();
        $this->assign('navthis', 'nav-this');
        $this->assign('cachePage', 'forum');
    }

    public function _404()
    {
        return $this->fetch('404');
    }

    public function index($page = 1)
    {
        /*$type = request()->param('type');
        $page = request()->param('page', 1);
        if (empty($type)) $type = 'all';
        $forum_model = new \app\model\Forum();
        $list = $forum_model->forumlist($type, $page);
        foreach ($list['lists'] as $key => $val) {
            $list['lists'][$key]['username'] = getByUserInfo($val['uid'], 'username');
            $list['lists'][$key]['avatar'] = getByUserInfo($val['uid'], 'headimgurl');
            $list['lists'][$key]['catename'] = getCageName($val['cate_id'], 'name');
            $list['lists'][$key]['reply'] = getReplayCount($val['id']);
        }
        $this->assign('type', $type);
        $this->assign('list', $list['lists']);
        $this->assign('allpage', $list['allpage']);
        $this->assign('nowpage', $list['nowpage']);*/
        $type = request()->param('type');
        switch ($type) {
            case "unsolved": //未结贴
                $where = "status=1 and accept=0";
                break;
            case "solved": //已采纳
                $where = "status=1 and accept=1";
                break;
            case "wonderful": //精华
                $where = "status=1 and elite=1";
                break;
            default:
                $where = "status=1";
        }
        if (empty($type)) $type = 'all';
        $forum_model = new \app\model\Forum();
        $filed = 'id,uid,title,top,elite,color,add_time,view,cate_id';
        $list = $forum_model->where($where)->field($filed)->order("top desc,id desc")->paginate(15, false, ['page' => $page]);
        foreach ($list as $key => $val) {
            $list[$key]['username'] = getByUserInfo($val['uid'], 'username');
            $list[$key]['avatar'] = getByUserInfo($val['uid'], 'headimgurl');
            $list[$key]['catename'] = getCageName($val['cate_id'], 'name');
            $list[$key]['reply'] = getReplayCount($val['id']);
            $list[$key]['add_time'] = wordTime($val['add_time']);
        }
        return $this->fetch('index', ['list' => $list, 'type' => $type,'title'=>'讨论']);
    }

    /**
     * ajax 获取列表内容
     * 这里晚上改造为TP获取
     * @return mixed|\think\response\Json
     */
    /*public function getIndex()
    {
        $type = request()->param('type');
        $page = request()->param('page', 1);
        if (empty($type)) $type = 'all';
        $forum_model = new \app\model\Forum();
        $list = $forum_model->forumlist($type, $page);
        foreach ($list['lists'] as $key => $val) {
            $list['lists'][$key]['username'] = getByUserInfo($val['uid'], 'username');
            $list['lists'][$key]['avatar'] = getByUserInfo($val['uid'], 'headimgurl');
            $list['lists'][$key]['catename'] = getCageName($val['cate_id'], 'name');
            $list['lists'][$key]['reply'] = getReplayCount($val['id']);
            $list['lists'][$key]['add_time'] = wordTime($val['add_time']);
        }
        return json($list);
    }*/
    //添加
    public function add()
    {
        if (request()->isPost()) {
            $answer = request()->param('answer');//获取人类验证的答案
            $vercode = request()->param('vercode');
            $user_model = new \app\model\User();
            $experience = $user_model->search(array('id' => $this->uid), "experience");
            $content = request()->param('content');
            $exp = request()->param('experience');//获取选择的悬赏金币
            $result = array();
            if ($vercode !== $answer) {
                $result = array('status' => 1, 'msg' => "人类验证失败");
            } elseif ($exp > 0 && $experience['experience'] < 0) {
                $result = array('status' => 1, 'msg' => "金币不足，多撸好贴赚银两去吧");
            } elseif (empty($content)) {
                $result = array('status' => 1, 'msg' => "内容不能为空");
            } else {
                $data = array(
                    'uid' => $this->uid,
                    'title' => request()->param('title'),
                    'content' => $content,
                    'cate_id' => request()->param('cate_id'),
                    'experience' => request()->param('experience'),
                    'add_time' => date('Y-m-d H:i:s')
                );
                if ($exp > 0) {
                    $expLog = new ExperienceLog();
                    $expLog->addForum($this->uid, $exp); //发布问答 扣除积分
                }
                $forum_model = new \app\model\Forum();
                if ($forum_model->add($data)) {
                    $result = array('status' => 0, 'action' => url('index/forum/index'));
                    //$this->redirect(url('/forum'));
                }
            }
            return json($result);
        } else {
            $this->checkLogin();
            $verify = $this->getVerify();
            $category_model = new Category();
            $cate = $category_model->getCategoryTree();
            $this->assign('verify', $verify);
            $this->assign('cate', $cate);
            $this->assign('title', '发表问题');
            return $this->fetch();
        }
    }

    //编辑
    public function edit()
    {
        $tid = request()->param('tid');
        $result = array();
        if (request()->isPost()) {
            $answer = request()->param('answer');//获取人类验证的答案
            $vercode = request()->param('vercode');
            $content = request()->param('content');
            if ($vercode !== $answer) {
                $result = array('status' => 1, 'msg' => "人类验证失败");
            } elseif (empty($content)) {
                $result = array('status' => 1, 'msg' => "内容不能为空");
            } else {
                $data = array(
                    'title' => request()->param('title'),
                    'content' => request()->param('content'),
                    'cate_id' => request()->param('cate_id'),
                    'experience' => request()->param('experience'),
                );
                $res = db('forum')->where(['id' => $tid])->update($data);
                if ($res) {
                    $result = array('status' => 0, 'msg' => "", "action" => url('index/forum/detail', ['tid' => $tid]));
                }
            }
            return json($result);
        } else {
            $this->checkLogin();
            $forum_model = new \app\model\Forum();
            $data = $forum_model->search(['id' => $tid]);
            if ($data['uid'] !== $this->uid) {
                $this->redirect(url('index/forum/detail', ['tid' => $tid]));
            }
            //判断当前用户是否是自己
            $verify = $this->getVerify();
            $category_model = new Category();
            $cate = $category_model->getCategoryTree();
            $this->assign('verify', $verify);
            $this->assign('cate', $cate);
            $this->assign('data', $data);
            return $this->fetch();
        }
    }

    //详情页
    public function detail()
    {
        $tid = request()->param('tid');
        $forum_model = new \app\model\Forum();
        $isup = $forum_model->updateView($tid);
        if (empty($isup)) {
            $this->redirect(url('index/index/_404'));
        }
        $data = $forum_model->search(['id' => $tid]);
        if (empty($data)) {
            $this->redirect(url('index/index/_404'));
        }
        $data['username'] = getByUserInfo($data['uid'], 'username');
        $data['avatar'] = getByUserInfo($data['uid'], 'headimgurl');
        $data['catename'] = getCageName($data['cate_id'], 'name');
        $data['reply'] = getReplayCount($data['id']);
        /*if($tid<18){
            $data['content'] = reply_replace($data['content']);
        }*/
        $reply = db('forum_reply')->where(['tid' => $tid, 'isdel' => 0])->order('reply_time asc')->select();
        foreach ($reply as $key => $val) {
            $reply[$key]['content'] = reply_replace_face($val['content']);
            $reply[$key]['username'] = getByUserInfo($val['uid'], 'username');
            $reply[$key]['avatar'] = getByUserInfo($val['uid'], 'headimgurl');
            $reply[$key]['level'] = getByUserInfo($val['uid'], 'level');
            $reply[$key]['lock'] = getByUserInfo($val['uid'], 'lock');
            $reply[$key]['time'] = strtotime($val['reply_time']);
            $reply[$key]['owner'] = 0;
            $reply[$key]['css_zan'] = 0;
            if ($data['uid'] == $val['uid']) {
                $reply[$key]['owner'] = 1;
            }
            if ($this->getZanStatus($val['id'])) {
                $reply[$key]['css_zan'] = 1;
            }
        }
        $hot_data = Top_Posts();
        $nearList = nearList();
        $this->assign('hot_data', $hot_data);
        $this->assign('nearList', $nearList);
        $this->assign('reply', $reply);
        $this->assign('data', $data);
        return $this->fetch();
    }


    public function tttt()
    {
        $content = "<img src=\"/uploads/attachment/201612/07/1481119352134637.jpg\" title=\"1481119352134637.jpg\" alt=\"0V3RDL22393L.jpg\">";
        $content = preg_replace('/\<img src=\"([^\s]+?)\".*?\>/s', '[图片]', $content);
        dump($content);
    }

    /**
     * 内容解析转换
     * @param $content
     */
    function reply_replaces($content)
    {
        //replace(/a\([\s\S]+?\)\[[\s\S]*?\]/g, function(str){ //转义链接
        //var href = (str.match(/a\(([\s\S]+?)\)\[/)||[])[1];
        //var text = (str.match(/\)\[([\s\S]*?)\]/)||[])[1];
        //if(!href) return str;
        $content = preg_replace('/&(?!#?[a-zA-Z0-9]+;)/s', '&amp;', $content);
        $content = preg_replace('/</s', '&lt;', $content);
        $content = preg_replace('/>/s', '&gt;', $content);
        $content = preg_replace('/\'/s', '&#39;', $content);
        $content = preg_replace('/"/s', '&quot;', $content);
        $content = preg_replace('/\[pre\](.*?)\[\/pre\]/s', '<pre>${1}</pre>', $content);
        $content = preg_replace('/@(\S+)(\s+?|$)/s', '@<a href="javascript:;" class="fly-aite">${1}</a>${2}', $content);
        $content = preg_replace('/img\[([^\s]+?)\]/s', '<img src="${1}">', $content);
        $content = preg_replace_callback('/face\[([^\s\[\]]+?)\]/s', 'getface', $content);
        $content = preg_replace('/a\([\s\S]+?\)\[(http:\/\/(\w+\.){2}\w+\/?\w+)]/s', '<a href="${1}" target="_blank" rel="nofollow">${1}</a>', $content);
        //$content = preg_replace('/\n/s','',$content);
        $content = str_replace(array("\r", "\r\n", "\n"), "<br>", $content);

        //$content = preg_replace('/\n/s','<br/>',$content);
        return $content;
    }

    /**
     * 提交回复
     */
    public function reply()
    {
        if (request()->isPost()) {
            $tid = request()->param('tid');
            $content = request()->param('content');
            if (empty($this->userinfo)) {
                $result = array('status' => 1, 'action' => false, 'msg' => '未登录');
                return json($result);
            } elseif (empty($content)) {
                $result = array('status' => 1, 'action' => false, 'msg' => '回复内容不能为空');
                return json($result);
            } elseif (strLength($content) < 10) {
                $result = array('status' => 1, 'action' => false, 'msg' => '回答太过简陋');
                return json($result);
            }
            preg_match("/([\x80-\xff]*+\w*+\s)/", $content, $match); //通过正则把to用户名匹配到
            $tousername = !empty($match) ? $match[0] : '';
            $where = ['username' => $tousername];
            $user_model = new \app\model\User();
            $touid = $user_model->search($where, 'id');
            $touid = !empty($touid) ? $touid['id'] : 0;
            $reply_time = date('Y-m-d H:i:s');
            $floorid = "#item-" . strtotime($reply_time);
            $data = array(
                'tid' => $tid,
                'uid' => $this->uid,
                'touid' => $touid,
                'floorid' => $floorid,
                'content' => $content,
                'reply_time' => $reply_time
            );
            if (db('forum_reply')->insert($data)) {
                $result = array('status' => 0, 'action' => false, 'msg' => '回答成功');
                return json($result);
            }
        }
    }

    /**
     * 编辑回复
     */
    public function getDa()
    {
        $id = request()->param('id'); //获得回复ID
        $data = db('forum_reply')->where(['id' => $id])->select();
        $rows = array();
        foreach ($data as $key => $val) {
            $rows['id'] = $val['id'];
            $rows['content'] = $val['content'];
        }
        $result = array('status' => 0, "rows" => $rows, "count" => count($rows));
        return json($result);
    }

    /**
     * 编辑回复更新
     */
    public function updateDa()
    {
        $id = request()->param('id'); //获得回复ID
        $content = request()->param('content');
        db('forum_reply')->where(['id' => $id])->update(['content' => $content]);
        $result = array('status' => 0, 'msg' => '更新成功');
        return json($result);
    }

    /**
     * 点击赞
     */
    public function jieda_zan()
    {
        $id = request()->param('id'); //获得回复ID
        $uid = $this->uid;
        //查询不能给自己点赞
        $data = db('forum_reply')->where(['id' => $id])->field('uid')->find();
        $ip = get_client_ip();
        if ($data['uid'] == $uid) {
            $result = array('status' => 1, 'msg' => '不要尝试给自己点赞');
        } else {
            //第一次点赞，第二次取消
            $check = db('zan')->where(['rid' => $id, 'uid' => $uid, 'isdel' => 0])->find();
            if ($check) {
                db('reply')->where(['id' => $id])->setDec('zan');
                db('zan')->where(['rid' => $id, 'uid' => $uid])->update(['isdel' => 1]);
                $result = array('status' => 0);
            } else {
                $insertData = array(
                    'rid' => $id,
                    'uid' => $uid,
                    'ip' => $ip,
                    'create_time' => date('Y-m-d H:i:s')
                );
                db('forum_reply')->where(['id' => $id])->setInc('zan');
                db('zan')->insert($insertData);
                $result = array('status' => 0);
            }
        }
        return json($result);
    }

    /**
     * 删除问答回复
     * ? 如果删除的问答回复是 采纳答案的，需要做一下操作
     * 1、将积分返还
     * 2、更改回复贴的状态 best = 0
     * 3、更改主题帖的状态 accept = 0
     */
    public function jieda_delete()
    {
        $id = request()->param('id'); //获得回复ID
        //$chk =db('reply')->where(['id'=>$id])->delete();
        $chk = db('forum_reply')->where(['id' => $id])->update(['isdel' => 1]);
        if ($chk) {
            $result = array('status' => 0, 'msg' => '删除成功');
        } else {
            $result = array('status' => 1, 'msg' => '删除失败');
        }
        return json($result);
    }

    /**
     * 删除问答
     */
    public function jie_delete()
    {
        $id = request()->param('id'); //获得问答ID
        $check = db('forum')->where(['id' => $id])->update(['status' => -1]);
        if ($check) {
            $result = array('status' => 0, 'msg' => '删除成功');
        } else {
            $result = array('status' => 1, 'msg' => '删除失败');
        }
        return json($result);
    }

    /**
     * 置顶
     */
    public function jie_set()
    {
        $id = request()->param('id'); //获得问答ID
        $rank = request()->param('rank'); //获取值
        $field = request()->param('field'); //获取字段
        $forum_model = new \app\model\Forum();
        $check = $forum_model->where(['id' => $id])->update([$field => $rank]);
        if ($check) {
            $expLog = new ExperienceLog();
            if ($field == 'elite' && $rank == 1) { //如果是加精需要奖励银两并记录日志
                $expLog->setElite($id, $rank);
            } elseif ($field == 'elite' && $rank == 0) {
                $expLog->setElite($id, $rank);
            }
            $result = array('status' => 0, 'msg' => '置顶成功');
        } else {
            $result = array('status' => 1, 'msg' => '置顶失败');
        }
        return json($result);
    }

    /**
     * 采纳
     * 1、采纳答案后，先更新reply表 best 为 1
     * 2、更新forum 表 accept 为 1
     * 3、需要将发布问答时的 银两 增加给 采纳答案的人
     *
     */
    public function jieda_accept()
    {
        $id = request()->param('id'); //获得回复ID
        $data = db('forum_reply')->where(['id' => $id])->field('uid,tid')->find(); //获取 回复ID中的 回复人员uid  和帖子id
        $chk1 = db('forum_reply')->where(['id' => $id])->update(['best' => 1]);
        $chk2 = db('forum')->where(['id' => $data['tid']])->update(['accept' => 1]);
        $expLog = new ExperienceLog();
        $expLog->setAccept($id);
        if ($chk1 && $chk2) {
            $result = array('status' => 0, 'msg' => '操作成功');
        } else {
            $result = array('status' => 1, 'msg' => '操作失败');
        }
        return json($result);
    }

    /**
     * 获取当前我是否点赞
     */
    public function getZanStatus($rid)
    {
        $reply_zan = Db::query("SELECT count(*) AS num FROM pe_zan AS zan LEFT JOIN pe_forum_reply AS reply ON reply.id = zan.rid
WHERE zan.isdel=0 AND reply.id =:rid AND zan.uid=:uid", ['rid' => $rid, 'uid' => $this->uid]);
        return $reply_zan[0]['num'];
    }

    //收藏，取消收藏的方法
    public function collection()
    {
        $type = request()->param('type');
        $tid = request()->param('tid');
        $collection_model = new Collection();
        $data = [
            'uid' => $this->uid,
            'tid' => $tid,
        ];
        //收藏的操作
        if ($type == "add") {
            $data['add_time'] = date('Y-m-d H:i:s');
            $collection_model->insert($data);
            $result['status'] = 0;
        } else {
            $collection_model->where($data)->delete();
            $result['status'] = 0;
        }
        return json($result);
    }

    //异步判断帖子是否收藏
    public function collectionFind()
    {
        $tid = request()->param('tid');
        $data = [
            'uid' => $this->uid,
            'tid' => $tid,
        ];
        $result['data'] = array();
        $collection_model = new Collection();
        if ($res = $collection_model->where($data)->find()) {
            $result['data']['collection'] = strtotime($res['add_time']);
        }
        $result['status'] = 0;
        return json($result);
    }
}